package com.zwz.controller;

import com.zwz.constant.CommonConstant;
import com.zwz.entity.User;
import com.zwz.exception.GlobalException;
import com.zwz.service.ChatSessionService;
import com.zwz.utils.R;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * 路由接口控制器
 *
 * @author
 *
 */
@Slf4j
@Controller
public class RouterController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ChatSessionService chatSessionService;

    /**
     * 登录接口
     *
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public R login(@RequestBody User user) {
        Set<String> keys = redisTemplate.keys(CommonConstant.USER_PREFIX + CommonConstant.REDIS_MATCH_PREFIX);
        if (keys != null && keys.size() > 0) {
            keys.forEach(key -> {
                User entity = chatSessionService.findById(key);
                if (entity != null) {
                    if ((entity.getName()).equals(user.getName())) {
                        throw new GlobalException("用户名已存在");
                    }
                }
            });
        }
        redisTemplate.boundValueOps(CommonConstant.USER_PREFIX + user.getId()).set(JSONObject.toJSONString(user));
        return new R();
    }

}
